<?php

class SJB_Admin_Classifieds_AddListing extends SJB_Function
{
	public function execute()
	{
		$tp = SJB_System::getTemplateProcessor();
		$listing_type_id = SJB_Request::getVar('listing_type_id', null);

		if (is_null($listing_type_id)) {
			$listing_types_info = SJB_ListingTypeManager::getAllListingTypesInfo();
			if (count($listing_types_info) == 1) {
				$listing_type_info = array_pop($listing_types_info);
				$listing_type_id = $listing_type_info['id'];
				SJB_HelperFunctions::redirect('?listing_type_id=' . $listing_type_id);
			}
			$tp->assign('listing_types_info', $listing_types_info);
			$tp->display('add_listing_choose_listing_type.tpl');
		}
		else {
			$listing_type_sid  = SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id);
			$listing_type_info = SJB_ListingTypeManager::getListingTypeInfoBySID($listing_type_sid);

			$listing_info = array_merge($_FILES, $_REQUEST);
			$listing = new SJB_Listing($listing_info, $listing_type_sid);

			// delete special JobG8 property from form
			$listing->deleteProperty('company_name');

			$add_listing_form = new SJB_Form($listing);
			$add_listing_form->registerTags($tp);

			$form_submitted = SJB_Request::getVar('action', '') == 'add';
			$tp->assign('listing_type_info', $listing_type_info);
			$errors = array();

			if ($form_submitted && $add_listing_form->isDataValid($errors)) {
				SJB_ListingManager::saveListing($listing);
				SJB_Event::dispatch('listingSaved', $listing->getSID());
				$tp->display('add_listing_success.tpl');
			}
			else {
				$tp->assign('errors', $errors);
				$tp->assign('object_sid', $listing->getSID());
				$tp->assign('form_fields', $add_listing_form->getFormFieldsInfo());
				$tp->assign('listing_type_id', $listing_type_id);
				$tp->display('input_form.tpl');
			}
		}
	}
}
